package com.scisoft.scan.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.scisoft.scan.data.PartNoBean;

import java.util.ArrayList;
import java.util.List;

public class PartDBHelper extends SQLiteOpenHelper {


    public PartDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, null, version);
    }

    //更新数据
    public int update(List<PartNoBean> partNoBeanList){
        int ret = -1;
        SQLiteDatabase db = getWritableDatabase();
        if(db.isOpen()){
            try{
                db.beginTransaction();
                db.execSQL("delete from part_info");
                if(partNoBeanList!=null){
                    for(int i = 0;i< partNoBeanList.size();i++){
                        String sql = String.format("insert into part_info values ('%s')", partNoBeanList.get(i).partNo);
                        db.execSQL(sql);
                    }
                }
                ret = 1;

            }catch(Exception e){
                ret = -1;
                e.printStackTrace();
            }finally{
                //显示的设置数据事务是否成功
                db.setTransactionSuccessful();
                db.endTransaction();
                db.close();
            }
        }
        return ret;
    }

    //查询全部数据
    public List<PartNoBean> query(){
        List<PartNoBean> ret = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT partNo FROM part_info", null);
        while (cursor.moveToNext()) {
            String partNo = cursor.getString(0);
            PartNoBean partNoBean = new PartNoBean();
            partNoBean.partNo = partNo;
            ret.add(partNoBean);
        }
        return ret;
    }

    //查询配件数量
    public int queryTotalCount() {
        int count = 0;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT count(1) FROM part_info", null);
        while (cursor.moveToNext()) {
            count = cursor.getInt(0);
        }
        cursor.close();
        return count;
    }

    //查询配件是否存在
    public int queryPartCount(String partNo) {
        int count = 0;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT count(1) FROM part_info where partNo = ? ", new String[]{partNo});
        while (cursor.moveToNext()) {
            count = cursor.getInt(0);
        }
        cursor.close();
        return count;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //参数表
        db.execSQL("CREATE TABLE if not exists part_info(partNo VARCHAR(100) PRIMARY KEY)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
